package com.wzf.utils;

import com.google.common.base.Charsets;
import org.caffinitas.ohc.CacheSerializer;

import java.nio.ByteBuffer;

//key-String 序列化器，这里直接复用OCH源码中测试用例的String序列化器
public class OhcStringSerializer implements CacheSerializer<String> {

    @Override
    public int serializedSize(String value) {
        return writeUTFLen(value);
    }

    @Override
    public void serialize(String value, ByteBuffer buf) {
        // 得到字符串对象UTF-8编码的字节数组
        byte[] bytes = value.getBytes(Charsets.UTF_8);
        buf.put((byte) ((bytes.length >>> 8) & 0xFF));
        buf.put((byte) ((bytes.length >>> 0) & 0xFF));
        buf.put(bytes);
    }


    @Override
    public String deserialize(ByteBuffer buf) {
        int length = (((buf.get() & 0xff) << 8) + ((buf.get() & 0xff) << 0));
        byte[] bytes = new byte[length];
        buf.get(bytes);
        return new String(bytes, Charsets.UTF_8);
    }
    static int writeUTFLen(String str) {
        int strlen = str.length();
        int utflen = 0;
        int c;

        for (int i = 0; i < strlen; i++) {
            c = str.charAt(i);
            if ((c >= 0x0001) && (c <= 0x007F)){
                utflen++;}
            else if (c > 0x07FF){
                utflen += 3;}
            else{
                utflen += 2;
            }
        }

        if (utflen > 65535) {
            throw new RuntimeException("encoded string too long: " + utflen + " bytes");
        }
        return utflen + 2;
    }
}


